<?php
namespace app\serverfund\logic;

use \app\manage\logic\BaseLogic;
use \think\Db;
/**
 * @author:      李颖
 * @DateTime:    2017-09-09 16:44:36
 * @Description: 充值
 */
class Recharge extends BaseLogic
{
    protected $name = 'pay_log';
    protected $config = 'db_config_fund';
    private $payLogModel = '\app\serverfund\model\PayLog';

    /*用户进行充值*/
    //添加充值记录在tp_pay_log记录表中
    //根据记录表中的id等所需参数进行请求支付宝二维码图片接口
    public function recharge($data): array 
    {
        
        $addPayLog['user_id'] = $data['user_id'];
        $addPayLog['app_id'] = $data['app_id'];
        $addPayLog['token'] = $data['token'];
        $addPayLog['action'] = 'recharge';
        $addPayLog['pay_type'] = $data['pay_type'];
        $addPayLog['recharge_type'] = $data['recharge_type'];
        $addPayLog['create_ip'] = $data['create_ip'];
        $addPayLog['money'] = $data['money'];
        $addPayLog['receive_param'] = $data;
        $addPayLog['return_param'] = [];
        $addPayLog['operate_steps'] = [];
        $addPayLog['steps_operate_result'] = [];
        $addPayLog['operate_result'] = 0;
        $getQrcode['body'] = $data['desc'];   //商品描述
        $getQrcode['attach'] = $data['attach'];  //附加信息
        $getQrcode['total_fee'] = $data['money'];
        $getQrcode['mch_create_ip'] = $data['create_ip'];
        $sqPay['goods_name'] = $data['desc'];
        $sqPay['phone_no'] = $data['phone_no'];
        $sqPay['customer_name'] = $data['customer_name'];
        $sqPay['cerd_id'] = $data['cerd_id'];
        $sqPay['card_no'] = $data['card_no'];
        $sqPay['cvn2'] = $data['cvn2'];
        $sqPay['valid_date'] = $data['valid_date'];
        $sqPay['amount'] = $data['money'];
        //添加一条记录
        $addPayLogRes = $this->model($this->payLogModel)->save($addPayLog);// 需要更新的一条记录中的数据
        if(!$addPayLogRes){
            return auto_failure(null, '添加一条充值记录失败');
        }
        $addPayLogId = $this->model($this->payLogModel)->getLastInsID();
        // 启动事务
        $this->db()->startTrans();
        try{
            $sqPay['merch_order_no'] = $addPayLogId;
            $getQrcode['out_trade_no'] = $addPayLogId;
            if($data['pay_type'] == 'unionpay'){  //使用衫齐无卡支付进行支付
                $sqPayRes = logic('app\serverfund\logic\SqBankCard')->sqPayOrder($sqPay);
                if($sqPayRes['status'] != SUCCESS_STATUS){
                    return $sqPayRes;
                }
                if($sqPayRes['res']['respCode'] != '00'){
                    return verify_err(null, $sqPayRes['res']['respMsg']);
                }
                //修改支付记录
                $_where['id'] = $addPayLogId;
                $savePay['return_param'] = $sqPayRes['res']['respData'];
                $saveRes = $this->model($this->payLogModel)->save($savePay, $_where);
                if(!$saveRes){
                    return auto_failure(null, '修改记录失败');
                }
                //设置返回结果
                $res['id'] = $addPayLogId;
            }else{  //获取支付宝和微信的二维码图片
                if($data['pay_type'] == 'alipay'){
                    $getQrcodeRes = logic('app\serverfund\logic\Alipay')->getAlipayQrcode($getQrcode); 
                }elseif($data['pay_type'] == 'wechat'){
                    $getQrcodeRes = logic('app\serverfund\logic\Wechat')->getWechatQrcode($getQrcode);
                }
                if($getQrcodeRes['status'] != SUCCESS_STATUS){
                    return $getQrcodeRes;
                }
                //修改支付记录
                $_where['id'] = $addPayLogId;
                $savePay['code_img_url'] = $getQrcodeRes['res']['code_img_url'];
                $savePay['sign'] = $getQrcodeRes['res']['sign'];
                $savePay['nonce_str'] = $getQrcodeRes['res']['nonce_str'];
                $saveRes = $this->model($this->payLogModel)->save($savePay, $_where);
                if(!$saveRes){
                    return auto_failure(null, '修改记录失败');
                }
                //设置返回结果
                $res['id'] = $addPayLogId;
                $res['code_img_url'] = $getQrcodeRes['res']['code_img_url'];
            }
            // 提交事务
            $this->db()->commit();  
            return auto_success($res, '操作成功');  
        } catch (\Exception $e) {
            // 回滚事务
            $this->db()->rollback();
            return server_err(null, '数据库异常:' . $e->getMessage());
        }
    }

    //支付订单时获取二维码   新增：添加字段操作步骤：operate_steps  steps_operate_result  operate_result 
    //后来也用于版本2 支付证书时，获取二维码
    public function getPayCode($data): array 
    {
        // 启动事务
        $this->db()->startTrans();
        $addPayLog['user_id'] = $data['user_id'];
        $addPayLog['app_id'] = $data['app_id'];
        $addPayLog['token'] = $data['token'];
        $addPayLog['action'] = $data['action'];
        $addPayLog['pay_type'] = $data['pay_type'];
        $addPayLog['recharge_type'] = $data['recharge_type'];
        $addPayLog['create_ip'] = $data['create_ip'];
        $addPayLog['money'] = $data['money'];
        $addPayLog['receive_param'] = $data;
        $addPayLog['return_param'] = [];
        $price = bcdiv($data['final_total_price'], 100, 2);
        //支付订单时，额外添加的字段 
        if($data['action'] == 'pay_order'){
            if($data['integral_deduction']){ 
                if($data['final_total_price']){  //支付方式  积分 + 人民币
                    $queryDataArray = [
                        ['path'=>'serverfund/fund/FundAccount/freeze', 'name'=>'冻结用户人民币' . $price . '元'],  //冻结用户人民币
                        ['path'=>'serverfund/integral/IntegralAccount/freeze', 'name'=>'冻结用户积分' . $data['integral_deduction'] . '个'],  //冻结用户积分
                        ['path'=>'serverorder/order/Order/payOrder', 'name'=>'支付订单'],  //修改订单状态为支付成功
                        ['path'=>'servercertificate/certificate/Certificate/applyAdvancedCertificate', 'name'=>'生成高级证书']
                    ];
                }else{   //支付方法  全积分
                    $queryDataArray = [
                        ['path'=>'serverfund/integral/IntegralAccount/freeze', 'name'=>'冻结用户积分' . $data['integral_deduction'] . '个'],  //冻结用户积分
                        ['path'=>'serverorder/order/Order/payOrder', 'name'=>'支付订单'],  //修改订单状态为支付成功
                        ['path'=>'servercertificate/certificate/Certificate/applyAdvancedCertificate', 'name'=>'生成高级证书']
                    ];
                }
            }else{    //支付方式  全人民币
                $queryDataArray = [
                    ['path'=>'serverfund/fund/FundAccount/freeze', 'name'=>'冻结用户人民币' . $price . '元'],  //冻结用户人民币
                    ['path'=>'serverorder/order/Order/payOrder', 'name'=>'支付订单'],  //修改订单状态为支付成功
                    ['path'=>'servercertificate/certificate/Certificate/applyAdvancedCertificate', 'name'=>'生成高级证书']
                ];
            }
        }else{
            $queryDataArray = [];
        }
        
        $addPayLog['operate_steps'] = $queryDataArray;
        $addPayLog['steps_operate_result'] = [];
        $addPayLog['operate_result'] = 0;
        $getQrcode['body'] = $data['desc'];
        $getQrcode['attach'] = $data['attach'];
        $getQrcode['total_fee'] = $data['money'];
        $getQrcode['mch_create_ip'] = $data['create_ip'];
        try{
            //添加一条记录
            $addPayLogRes = $this->model($this->payLogModel)->save($addPayLog);
            // 需要更新的一条记录中的数据
            if(!$addPayLogRes){
                return auto_failure(null, '添加一条充值记录失败');
            }
            $addPayLogId = $this->model($this->payLogModel)->getLastInsID();
            $getQrcode['out_trade_no'] = $addPayLogId;
            //获取扫描二维码图片
            if($data['pay_type'] == 'alipay'){
                $getQrcodeRes = logic('app\serverfund\logic\Alipay')->getAlipayQrcode($getQrcode);
            }elseif($data['pay_type'] == 'wechat'){
                $getQrcodeRes = logic('app\serverfund\logic\Wechat')->getWechatQrcode($getQrcode);
            }elseif($data['pay_type'] == 'unionpay'){
                $getQrcodeRes = logic('app\serverfund\logic\Unionpay')->getUnionpayQrcode($getQrcode);
            }
            if($getQrcodeRes['status'] != SUCCESS_STATUS){
                return $getQrcodeRes;
            }

            //修改支付记录
            $_where['id'] = $addPayLogId;
            $savePay['code_img_url'] = $getQrcodeRes['res']['code_img_url'];
            $savePay['sign'] = $getQrcodeRes['res']['sign'];
            $savePay['nonce_str'] = $getQrcodeRes['res']['nonce_str'];
            $saveRes = $this->model($this->payLogModel)->save($savePay, $_where);
            if(!$saveRes){
                return auto_failure(null, '修改记录失败');
            }

            //设置返回结果
            $res['id'] = $addPayLogId;
            $res['code_img_url'] = $getQrcodeRes['res']['code_img_url'];
            // 提交事务
            $this->db()->commit();  
            return auto_success($res, '成功获取二维码');  
        } catch (\Exception $e) {
            // 回滚事务
            $this->db()->rollback();
            return server_err(null, '数据库异常:' . $e->getMessage());
        }
    }
    //使用杉奇无卡支付进行支付订单
    public function sqPayOrder($data): array 
    {
        $addPayLog['user_id'] = $data['user_id'];
        $addPayLog['app_id'] = $data['app_id'];
        $addPayLog['token'] = $data['token'];
        $addPayLog['action'] = $data['action'];
        $addPayLog['pay_type'] = $data['pay_type'];
        $addPayLog['recharge_type'] = $data['recharge_type'];
        $addPayLog['create_ip'] = $data['create_ip'];
        $addPayLog['money'] = $data['money'];
        $addPayLog['receive_param'] = $data;
        $addPayLog['return_param'] = [];
        $price = bcdiv($data['final_total_price'], 100, 2);
        //支付订单时，额外添加的字段 
        if($data['action'] == 'pay_order'){
            if($data['integral_deduction']){ 
                if($data['final_total_price']){  //支付方式  积分 + 人民币
                    $queryDataArray = [
                        ['path'=>'serverfund/fund/FundAccount/freeze', 'name'=>'冻结用户人民币' . $price . '元'],  //冻结用户人民币
                        ['path'=>'serverfund/integral/IntegralAccount/freeze', 'name'=>'冻结用户积分' . $data['integral_deduction'] . '个'],  //冻结用户积分
                        ['path'=>'serverorder/order/Order/payOrder', 'name'=>'支付订单'],  //修改订单状态为支付成功
                        ['path'=>'servercertificate/certificate/Certificate/applyAdvancedCertificate', 'name'=>'生成高级证书']
                    ];
                }else{   //支付方法  全积分
                    $queryDataArray = [
                        ['path'=>'serverfund/integral/IntegralAccount/freeze', 'name'=>'冻结用户积分' . $data['integral_deduction'] . '个'],  //冻结用户积分
                        ['path'=>'serverorder/order/Order/payOrder', 'name'=>'支付订单'],  //修改订单状态为支付成功
                        ['path'=>'servercertificate/certificate/Certificate/applyAdvancedCertificate', 'name'=>'生成高级证书']
                    ];
                }
            }else{    //支付方式  全人民币
                $queryDataArray = [
                    ['path'=>'serverfund/fund/FundAccount/freeze', 'name'=>'冻结用户人民币' . $price . '元'],  //冻结用户人民币
                    ['path'=>'serverorder/order/Order/payOrder', 'name'=>'支付订单'],  //修改订单状态为支付成功
                    ['path'=>'servercertificate/certificate/Certificate/applyAdvancedCertificate', 'name'=>'生成高级证书']
                ];
            }
        }else{
            $queryDataArray = [];
        }
        
        $addPayLog['operate_steps'] = $queryDataArray;
        $addPayLog['steps_operate_result'] = [];
        $addPayLog['operate_result'] = 0;
        $sqPayOrder['goods_name'] = $data['desc'];
        $sqPayOrder['phone_no'] = $data['phone_no'];
        $sqPayOrder['customer_name'] = $data['customer_name'];
        $sqPayOrder['cerd_id'] = $data['cerd_id'];
        $sqPayOrder['card_no'] = $data['card_no'];
        $sqPayOrder['cvn2'] = $data['cvn2'];
        $sqPayOrder['valid_date'] = $data['valid_date'];
        $sqPayOrder['amount'] = $data['money'];
        //添加一条记录
        $addPayLogRes = $this->model($this->payLogModel)->save($addPayLog);
        // 需要更新的一条记录中的数据
        if(!$addPayLogRes){
            return auto_failure(null, '添加一条充值记录失败');
        }
        $addPayLogId = $this->model($this->payLogModel)->getLastInsID();
        // 启动事务
        $this->db()->startTrans();
        try{
            $sqPayOrder['merch_order_no'] = $addPayLogId;
            //使用杉奇无卡支付进行支付
            $sqPayOrderRes = logic('\app\serverfund\logic\SqBankCard')->sqPayOrder($sqPayOrder);
            if($sqPayOrderRes['status'] != SUCCESS_STATUS){
                return $sqPayOrderRes;
            }
            if($sqPayOrderRes['res']['respCode'] != '00'){
                return verify_err(null, $sqPayOrderRes['res']['respMsg']);
            }

            //修改支付记录
            $_where['id'] = $addPayLogId;
            $savePay['return_param'] = $sqPayOrderRes['res']['respData'];
            $saveRes = $this->model($this->payLogModel)->save($savePay, $_where);
            if(!$saveRes){
                return auto_failure(null, '修改记录失败');
            }
            //设置返回结果
            $res['id'] = $addPayLogId;
            // 提交事务
            $this->db()->commit();
            return auto_return($res, $sqPayOrderRes['res']['respData']['respMsg']);  
        } catch (\Exception $e) {
            // 回滚事务
            $this->db()->rollback();
            return server_err(null, '数据库异常:' . $e->getMessage());
        }
    }

    /*判断是否已充值成功*/
    public function isRecharge($data): array 
    {
        $_where['id'] = $data['id'];
        $res = $this->model($this->payLogModel)->where($_where)->find();
        if(!$res){
            return auto_failure(null, '未找到相关记录');
        }
        //返回数据
        $returnData['status'] = $res['status'];
        $returnData['result_status'] = $res['result_status'];

        if($res['status'] == 0){
            $returnData['msg'] = '等待支付...';
        }elseif($res['status'] == 1){
            if($res['result_status'] == 1){
                $returnData['msg'] = '充值成功！';
            }else{
                $returnData['msg'] = '支付成功，充值失败，请联系客服';
            }
        }else{
            $returnData['msg'] = '支付失败，请重试！';
        }
        return auto_success($returnData, $returnData['msg']);
    }

    /*根据id获取该条支付记录 第三方支付订单开始*/
    public function getPayInfo($data): array 
    {
        $_where['id'] = $data['id'];
        $res = $this->model($this->payLogModel)->lock(true)->where($_where)->find();
        return auto_return($res, '成功获取该条支付记录', '获取该条支付记录失败');
    }
    /*根据id修改该支付记录 第三方支付订单结束*/
    public function updatePayLog($data): array 
    {
        $_where['id'] = $data['id'];
        $saveData['steps_operate_result'] = $data['steps_operate_result'];
        $saveData['operate_result'] = $data['operate_result'];
        $res = $this->model($this->payLogModel)->save($saveData, $_where);
        return auto_return($res, '成功修改该条支付记录', '修改该条支付记录失败');
    }

}




